package com.ksyun.common.util;

import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.MDC;


public class TraceUtils {

	public static final String TRACE_ID = "traceId";
	private static final int TRACE_ID_LENGTH = 8;

	public static String genTraceId(){
		return RandomStringUtils.randomAlphanumeric(TRACE_ID_LENGTH);
	}

	/**
	 * 开始Trace, 默认生成本次Trace的ID(8字符长)并放入MDC.
	 */
	public static void beginTrace() {
		String traceId = RandomStringUtils.randomAlphanumeric(TRACE_ID_LENGTH);
		MDC.put(TRACE_ID, traceId);
	}

	/**
	 * 开始Trace, 将traceId放入MDC.
	 */
	public static void beginTrace(String traceId) {
		MDC.put(TRACE_ID, traceId);
	}

	/**
	 * 结束一次Trace.
	 * 清除traceId.
	 */
	public static void endTrace() {
		MDC.remove(TRACE_ID);
	}
}
